package com.gewu.pm.http.callback;

import android.app.Activity;

import androidx.annotation.NonNull;

import com.gewu.pm.action.ToastAction;
import com.gewu.pm.ui.dialog.Wait2Dialog;
import com.hjq.base.BaseDialog;
import com.hjq.http.config.IRequestApi;
import com.hjq.http.listener.HttpCallbackProxy;

/**
 * 网络加载弹框
 * @param <T>
 */
public abstract class DialogCallback<T> extends HttpCallbackProxy<T> implements ToastAction {

    private BaseDialog mDialog;
    private Activity activity;

    private void initDialog(Activity activity) {
        this.activity = activity;
        if (mDialog == null) {
            mDialog = new Wait2Dialog.Builder(activity)
                    .setCancelable(false)
                    .create();
        }
        if (!mDialog.isShowing()) {
            mDialog.show();
        }

    }

    public DialogCallback(Activity activity) {
        super(null);
        initDialog(activity);
    }

    @Override
    public void onHttpSuccess(T result) {
        super.onHttpSuccess(result);
    }

    @Override
    public void onHttpStart(@NonNull IRequestApi api) {
        super.onHttpStart(api);

        if (!activity.isFinishing()) {
            mDialog.show();
        }
    }

    @Override
    public void onHttpEnd(@NonNull IRequestApi api) {
        super.onHttpEnd(api);

        if (mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onHttpFail(@NonNull Throwable e) {
        super.onHttpFail(e);
        toast(e.getMessage());
        if (mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }
}
